package com.key.sys.apps.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;

import com.key.base.action.BaseAction;
import com.key.sys.apps.model.App;
import com.key.sys.apps.service.IAppService;
import com.key.util.HibernateUtil;
import com.key.util.XspMessage;

public class AppAction extends BaseAction {

	IAppService appService;
	private App app;

	public App getApp() {
		return app;
	}

	public void setApp(App app) {
		this.app = app;
	}

	public IAppService getAppService() {
		if (appService == null)
			appService = (IAppService) getBean("appServiceImp");
		return appService;
	}

	public void setAppService(IAppService appService) {
		this.appService = appService;
	}

	@Override
	public String save() {
		// TODO Auto-generated method stub
		XspMessage xspMessage = new XspMessage();
		try {
			// check

			getAppService().add(app);
		} catch (Exception e) {
			return xspMessage
					.setMessage("保存失败", e.toString(), XspMessage.ERROR);
		}
		return "Success";
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		XspMessage xspMessage = new XspMessage();
		try {
			// check

			getAppService().update(app);
		} catch (Exception e) {
			return xspMessage
					.setMessage("更新失败", e.toString(), XspMessage.ERROR);
		}
		return "Success";
	}

	public String forwardApp() {
		// TODO Auto-generated method stub
		XspMessage xspMessage = new XspMessage();
		try {
			// check

			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			HttpServletRequest request = ServletActionContext.getRequest();
			String id = request.getParameter("appid");
			if (id == null || id.equals("")) {
				return xspMessage.setMessage("转向应用失败", "App id获取失败",
						XspMessage.ERROR);
			} else {
				String hql = "from App app where app.id = '" + id + "'";
				List list = session.createQuery(hql).list();
				session.getTransaction().commit();
				if (list == null || list.size() <= 0) {
					return xspMessage.setMessage("转向应用失败", "没有查询到此应用",
							XspMessage.ERROR);
				} else {
					App app = (App) list.get(0);
					request.setAttribute("treePath", app.getAppLink());
				}
			}
		} catch (Exception e) {
			return xspMessage.setMessage("转向应用失败", e.toString(),
					XspMessage.ERROR);
		}
		return "treePath";
	}
}
